package cn.edu.neu.softlab.jason.offer.jianzhioffer.datastructure;

/**
 * 剑指offer-面试4衍生题
 * 有两个排序数组A1和A2，内存在A1的末尾有足够多的空余空间容纳A2。请事先一个函数，把A2中的所有数字插入
 * 到A1中并且所有数字都是排序的。
 */
public class Mianshi4_1 {
    public static void main(String[] args) {
        int[] a = {1, 3, 8, 11, 0, 0, 0, 0, 0};
        int[] b = {2, 5, 6, 9};
        insertArray(a, b, 4, 4);
        for (int i = 0; i < 8; i++) {
            System.out.print(a[i]);
        };
    }

    public static void insertArray(int[] a, int[] b, int lengtha, int lengthb) {
        if (a == null || b == null || lengtha < 0 || lengthb < 0) {
            return;
        }

        int newlength = lengtha + lengthb;
        int apos = lengtha - 1;
        int newpos = newlength - 1;
        int bpos = lengthb - 1;

        while (newpos >= 0 && apos >= 0 && bpos >= 0) {
            int tmp;
            if (a[apos] > b[bpos]) {
                tmp = a[apos];
                apos--;
            } else {
                tmp = b[bpos];
                bpos--;
            }
            a[newpos] = tmp;
            newpos--;
        }
    }
}
